/*
 * Filter for user authentication
 */
package com.spartancoder.accommodation.filters;

import com.spartancoder.accommodation.models.AuthToken;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author andrei
 */
public class AuthFilter implements Filter {

	private static Logger log = Logger.getLogger(AuthFilter.class.getName());
	private FilterConfig config = null;

	public void init(FilterConfig filterConfig) throws ServletException {
		config = filterConfig;
	}

	public void doFilter(ServletRequest req0, ServletResponse resp0, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req0;
		HttpServletResponse response = (HttpServletResponse) resp0;

		HttpSession session = request.getSession();
		AuthToken authToken = new AuthToken(session);
		request.setAttribute("authToken", authToken);

		String context = request.getContextPath();
		String uri = request.getRequestURI().substring(context.length());

		/*
		 * Do url checking for public content
		 */
		String guestSection = config.getInitParameter("guestSection");
		if (guestSection != null) {
			String[] parts = guestSection.split(",");
			for (String p : parts) {
				if (uri.matches(p)) {
					chain.doFilter(req0, resp0);
					return;
				}
			}
		}

		/*
		 * Check student restricted section
		 */
		String studentSection = config.getInitParameter("studentSection");
		if (studentSection != null) {
			String[] parts = studentSection.split(",");
			for (String p : parts) {
				if (uri.matches(p)) {
					if (authToken.isStudent()) {
						chain.doFilter(req0, resp0);
						return;
					} else {
						response.sendRedirect(context + "/index.jsp");
						return;
					}
				}
			}
		}

		/*
		 * Check admin restricted section
		 */
		String adminSection = config.getInitParameter("adminSection");
		if (adminSection != null) {
			String[] parts = adminSection.split(",");
			for (String p : parts) {
				if (uri.matches(p)) {
					if (authToken.isAdmin()) {
						chain.doFilter(req0, resp0);
						return;
					} else {
						response.sendRedirect(context + "/index.jsp");
						return;
					}
				}
			}
		}

		chain.doFilter(req0, resp0);
	}

	public void destroy() {
		config = null;
	}
}
